import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { Session } from '@/utils/storage';
import { VueAxios } from './axios'
import { Modal, notification } from 'ant-design-vue'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || "/jwApi", // api base_url
  timeout: 200000 // 请求超时时间
})

const err = (error) => {
  if (error.isAxiosError) {
    notification.error({ message: '系统提示', description: error.message, duration: 4 })
  } else {
    let data = error.response.data
    const token = store.state.user.accessToken

    switch (error.response.status) {
      case 403:
        notification.error({ message: '系统提示', description: '拒绝访问', duration: 4 })
        break
      case 500:
        {
          let path = window.location.href
          //notification.error({ message: '系统提示', description:'Token失效，请重新登录!',duration: 4})
          if (token && data.message.includes("Token失效") && path.indexOf('/login') < 0) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  try {
                    if(path.indexOf('/login') === -1){
                      window.location.reload()
                    }
                  }catch (e) {
                    window.location.reload()
                  }
                })
              }
            })
            // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
          }
          break
        }
      case 404:
        notification.error({ message: '系统提示', description: '很抱歉，资源未找到!', duration: 4 })
        break
      case 403:
        notification.error({ message: '系统提示', description: '没有操作权限', duration: 4 })
        break
      case 504:
        notification.error({ message: '系统提示', description: '网络超时' })
        break
      case 401:
        notification.error({ message: '系统提示', description: '未登录或者登录已过期，请重新登录', duration: 4 })
        if (token) {
          // store.dispatch('Logout').then(() => {
          //   setTimeout(() => {
          //     window.location.reload()
          //   }, 1500)
          // })
        }
        break
      default:
        notification.error({
          message: '系统提示',
          description: data.message,
          duration: 4
        })
        break
    }
  }
  return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
  const token = store.state.user.accessToken
  if (token) {
    config.headers['accessToken'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {
  const code = response.data.code
  const error = {}
  error.response = response.data
  if (code && code !== 0 && code !== 200) {
    if (code === 401) {
      Modal.error({
        title: '登录已过期',
        content: '很抱歉，登录已过期，请重新登录',
        okText: '重新登录',
        mask: false,
        onOk: () => {
          store.dispatch('Logout').then(() => {
            // Session.remove(ACCESS_TOKEN);
            store.commit('SET_TOKEN', '')
            window.location.reload()
          })
        }
      })
    } else if (code === 403) {
      notification.error({ message: '系统提示', description: '没有操作权限', duration: 4 })
      return Promise.reject(error)
    } else {
      if (code < 0) {
        Modal.error({
          title: '错误提示',
          content: response.data.message || '系统异常'
        })
      } /*** 大于0的提示自行处理
      else {
        notification.warn({
          message: '提示',
          description: response.data.message || '系统异常'
        })
      } */
      return Promise.reject(error)
    }
  } else {
    return response.data
  }
}, err)

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
